import socket


#设置服务器参数

IP = '127.0.0.1'#本地回环地址
PORT = 8080 #端口

def handle_request(client_socket):
    """处理客户端请求并返回响应"""
    #接收客户端请求数据，最多1024字节
    request_data = client_socket.recv(1024).decode()
    print(f"Received Request:\n{request_data}")

    #请求解析第一行
    request_line = request_data.split('\r\n')[0]
    method,path,protocol = request_line.split()

    if path == '/':
        status_code = 200
        response_body = "<h1>welcome to simple web server header page</h1>"
    elif path == "/about":
        status_code = 200
        response_body = "<h1>welcome to simple web server about page</h1>"
    else:
        status_code = 404
        response_body = "<h1>Not Found</h1>"
    status_line = f"HTTP/1.1 {status_code} {'Ok' if status_code == 200 else 'Not Found'}\r\n"
    headers = "Content-Type:text/html\r\n"
    headers += f"Content-length:{len(response_body)}\r\n"
    headers += f"Connection:close\r\n"#关闭连接
    response = f"{status_line}{headers}\r\n{response_body}"

    client_socket.sendall(response.encode())
    client_socket.close()

def run_server():
    """启动服务器并持续监听连接"""

    #创建TCP Socket
    with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as server_socket:
        #设置端口复用
        server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
        
        #绑定地址和端口
        server_socket.bind((IP,PORT))
        #开始监听，最多5个等待连接
        server_socket.listen(5)
        print(f"Server running on http://{IP}:{PORT}")

        while True:
            client_socket,addr = server_socket.accept()
            print(f"Connected by{addr}")
            handle_request(client_socket)

if __name__ == "__main__":
    run_server()


        
